package app.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JButton;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import app.ui.QuestionUI;

public class PlayerAction implements ActionListener, Runnable {
	private QuestionUI mPanel;
	private File file;
	private Player player;
	private Thread thread;

	public PlayerAction(QuestionUI mPanel) {
		this.mPanel = mPanel;
		String lastDir = mPanel.getmFrame().getDataFileDir().getAbsolutePath();
		String fileName = mPanel.getmFrame().getTextSource().getPathFilemp3();

		if (mPanel.getmFrame().getTextSource() != null) {
			this.file = new File(lastDir + "/" + fileName);
		}

		// set the media location for media player
		URL url = null;
		try {
			url = new URL("file:/" + file.getAbsolutePath());
			mPanel.getMediaPlayer().setMediaLocation(url.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	public void actionPerformed(ActionEvent e) {
		JButton jButton = (JButton) e.getSource();

		if (jButton.getText().equals(mPanel.getBtnLables()[0])) { // play
			// playAudioFile(jButton, file);
			mPanel.getMediaPlayer().start();
			jButton.setEnabled(false);
		} else if (jButton.getText().equals(mPanel.getBtnLables()[1])) { // stop
			// stopPlayAudioFile(mPanel.getjButtons()[0]);
			mPanel.getMediaPlayer().stop();
			mPanel.getjButtons()[0].setEnabled(true);
		}
	}

	@SuppressWarnings("unused")
	private void playAudioFile(JButton jButton, File file) {
		stopPlayAudioFile(mPanel.getjButtons()[0]);

		if (file != null) {
			try {
				InputStream in = new FileInputStream(file);

				player = new Player(in);
				thread = new Thread(this);

				thread.start();

				jButton.setEnabled(false);
				mPanel.setIndex(0);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (JavaLayerException e) {
				e.printStackTrace();
			}
		}
	}

	private void stopPlayAudioFile(JButton jButton) {
		if (player != null) {
			player.close();
			player = null;
		}
		thread = null;
		jButton.setEnabled(true);
	}

	public void run() {
		try {
			if (player != null) {
				player.play();
			}

			stopPlayAudioFile(mPanel.getjButtons()[0]);
		} catch (JavaLayerException e) {
			e.printStackTrace();
		}
	}
}
